package top.csy8888.ch05.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.support.converter.DefaultJackson2JavaTypeMapper;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;

/**
 * @author CSY
 * @date 2025 - 10 - 11
 * 方式一
 * 在配置类中装配交换机、队列并绑定
 */
@Configuration
public class RabbitConfig {
    /**
     * 交换机名称
     */
    public final static String EXCHANGE_NAME = "order.exchange";
    /**
     * 队列名称
     */
    public final static String QUEUE_NAME = "order.queue";
    /**
     * 路由的key
     */
    public final static String ROUTING_KEY = "order.key";

    /**
     * 装配direct类型的交换机
     */
//    @Bean
    public Exchange exchange() {
//        return new TopicExchange(EXCHANGE_NAME);
//        return new FanoutExchange(EXCHANGE_NAME);
        return new DirectExchange(EXCHANGE_NAME);
    }

    /**
     * 装配队列
     */
//    @Bean
    public Queue queue() {
        // 参数二：是否持久化
        return new Queue(QUEUE_NAME,false);
    }

    /**
     * 将队列和交换机进行绑定
     */
//    @Bean
    public Binding binding() {
        //绑定队列到交换机上基于ROUTING_KEY
        return BindingBuilder
                .bind(queue())
                .to(exchange())
                .with(ROUTING_KEY)
                .noargs();
    }

    /**
     * 重新装配默认的序列化器SimpleMessageConverter
     * 添加允许反序列化的类
     */
    /*@Bean
    public SimpleMessageConverter messageConverter() {
        SimpleMessageConverter converter = new SimpleMessageConverter();
        // 添加允许反序列化的类
        converter.setAllowedListPatterns(Arrays.asList("top.csy8888.ch05.dto.Order", "top.csy8888.ch05.dto.*"));
        return converter;
    }*/

    /**
     * 使用JSON的序列化器进行序列化和反序列化
     * 替换默认的SimpleMessageConverter序列化器
     * @return
     */
    @Bean
    public MessageConverter jackson2JsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }
}
